package cn.com.pc.content.controller;

import cn.com.pc.content.annotation.LogRequired;
import cn.com.pc.content.domain.Biz;
import cn.com.pc.content.domain.Site;
import cn.com.pc.content.domain.tag.Tag;
import cn.com.pc.content.domain.tag.TagNotFoundException;
import cn.com.pc.content.domain.tag.TagTree;
import cn.com.pc.content.domain.tag.TagTreeNotFoundException;
import cn.com.pc.content.dto.*;
import cn.com.pc.content.service.TagService;
import cn.com.pc.content.service.TagTreeService;
import cn.com.pc.content.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 标签管理
 *
 */
@RestController
@RequestMapping("/tags")
@Slf4j
public class TagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private TagTreeService tagTreeService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 新增标签
     * @param tagDTO
     * @return
     */
    @PostMapping
    @LogRequired(operation = "'新增标签' + #_return")
    public Long createTag(@RequestAttribute("site") Site site, @RequestAttribute("biz") Biz biz, @Validated @RequestBody TagDTO tagDTO) {
        // 判空
        if (tagDTO.getTreeId() != null) {
            TagTree tagTree = tagTreeService.getTagTreeById(tagDTO.getTreeId());
            if (tagTree == null) {
                throw new TagTreeNotFoundException();
            }
            tagDTO.setTreeName(tagTree.getName());
        }

        // 查重
        Tag tag = tagService.getTagByName(site, biz, tagDTO.getName());
        if (tag != null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "标签名称已存在");
        }

        tagDTO.setSite(site);
        tagDTO.setBiz(biz);
        tagDTO.setCreatedAt(LocalDateTime.now());
        tagDTO.setUpdatedAt(LocalDateTime.now());
        return tagService.createTag(tagDTO);
    }


    /**
     * 修改标签
     * @param tagId
     * @return
     */
    @PutMapping("/{tagId:\\d+}")
    @LogRequired(operation = "'修改标签' + #tagId")
    public Tag updateTag(@PathVariable("tagId") Long tagId, @RequestAttribute("site") Site site, @RequestAttribute("biz") Biz biz, @Validated @RequestBody TagDTO tagDTO) {
        // 判空
        Tag tag = tagService.getTagById(tagId);
        if (tag == null || tag.getSite() != site) {
            throw new TagNotFoundException();
        }
        tagDTO.setCreatedAt(tag.getCreatedAt());

        if (tagDTO.getTreeId() != null) {
            TagTree tagTree = tagTreeService.getTagTreeById(tagDTO.getTreeId());
            if (tagTree == null) {
                throw new TagNotFoundException();
            }
            tagDTO.setTreeName(tagTree.getName());
        }

        // 查重
        if (!tag.getName().equals(tagDTO.getName())) {
            if (tagService.getTagByName(site, biz, tagDTO.getName()) != null) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "标签名称已存在");
            }
        }

        tagDTO.setSite(site);
        tagDTO.setBiz(biz);
        tagDTO.setUpdatedAt(LocalDateTime.now());
        tagDTO.setId(tagId);

        try {
            request.setAttribute("operation", "，修改属性" + BeanUtils.comparePropertyIgnore(tag, tagDTO, "id", "createdAt", "updatedAt", "leftRelations", "rightRelations", "treeName"));
        } catch (Exception e) {
            log.warn("标签{}生成修改日志有误", tagId);
            e.printStackTrace();
        }
        return tagService.updateTag(tagDTO, tag);
    }


    /**
     * 删除标签（暂不提供）
     * @param tagId
     */
//    @DeleteMapping("/{tagId:\\d+}")
    public void deleteTag(@PathVariable("tagId") Long tagId, @RequestAttribute("site") Site site, @RequestAttribute(value = "biz", required = false) Biz biz) {
        // 判空
        Tag tag = tagService.getTagById(tagId);
        if (tag == null || tag.getSite() != site) {
            throw new TagNotFoundException();
        }
        // 校验标签是否使用中

        tagService.deleteTag(tag);
    }


    /**
     * ES查询标签列表
     * @param site
     * @param biz
     * @param tagForm
     * @param pageForm
     * @param sort
     * @return
     */
    @GetMapping
    public PageResult<TagDTO> listTagsByForm(@RequestAttribute("site") Site site, @RequestAttribute(value = "biz", required = false) Biz biz, TagForm tagForm, PageForm pageForm, Sort sort) {
        tagForm.setSite(site);
        tagForm.setBiz(biz);
        return tagService.listTagsByForm(tagForm, pageForm, sort);
    }


    /**
     * ES查询标签详情
     * @param tagId
     * @return
     */
    @GetMapping("/{tagId:\\d+}")
    public TagDTO getTagById(@PathVariable("tagId") Long tagId, @RequestAttribute("site") Site site, @RequestAttribute(value = "biz", required = false) Biz biz) {
        TagDTO tagDTO = tagService.searchTagById(tagId);
        if (tagDTO == null || tagDTO.getSite() != site) {
            throw new TagNotFoundException();
        }
        return tagDTO;
    }

}
